﻿using QRCodeTools.Utils;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using ZXing;
using ZXing.Common;
using ZXing.Multi.QrCode;

namespace QRCodeTools {
    public partial class MainForm : Form {
        private ScreenCaptureForm screenCaptureForm = new ScreenCaptureForm();
        private CmdParamsHandlerMgr CmdHandlerMgr = new CmdParamsHandlerMgr();
        private string[] RunArgs = null;
        private void HideUI() {
            ShowInTaskbar = false;
            WindowState = FormWindowState.Minimized;
        }
        private void ShowUI() {
            ShowInTaskbar = true;
            WindowState = FormWindowState.Normal;
        }
        private void StartCmdHandler(string[] args) {
            if (args != null && args.Length > 0) {
                //有参数启动,则隐藏界面,
                HideUI();
                RunArgs = args;
            }
        }
        private void TriggerCmdHandler() {
            if (RunArgs != null) {
                if (!CmdHandlerMgr.TriggerHandlers(RunArgs)) {
                    //没匹配到,则直接显示界面
                    ShowUI();
                }
            }
        }
        private void EndCmdHandler() {
            if (RunArgs != null) {
                ShowUI();
            }
            RunArgs = null;
        }

        public MainForm(string[] args) {

            CmdHandlerMgr.RegCmd(new Action(CmdParseScreenQRCode), this, "-ScreenParse", "-sp");
            CmdHandlerMgr.RegCmd(new Action(CmdParseClipboardQRCode), this, "-ClipboardParse", "-cp");

            InitializeComponent();
            screenCaptureForm.OnScreenCapture += ScreenCaptureForm_OnScreenCapture;
            screenCaptureForm.OnEndCapture += ScreenCaptureForm_OnEndCapture;

            StartCmdHandler(args);

            Text+= " V"+Assembly.GetExecutingAssembly().GetName().Version.ToString();
        }


        private void CmdParseScreenQRCode() {
            BtnParseScreenQRCode_Click(BtnParseScreenQRCode, EventArgs.Empty);
        }
        private void CmdParseClipboardQRCode() {
            BtnParseClipboardQRCode_Click(BtnParseClipboardQRCode, EventArgs.Empty);
            EndCmdHandler();
        }

        #region 屏幕二维码识别
        private void BtnParseScreenQRCode_Click(object sender, EventArgs e) {
            Opacity = 0;
            screenCaptureForm.Show();
        }
        private void ScreenCaptureForm_OnEndCapture(object sender, EventArgs e) {
            Opacity = 1;
            EndCmdHandler();
        }
        private void ScreenCaptureForm_OnScreenCapture(Bitmap screenImage) {
            Result[] r = QRCodeHelper.ParseQRCode(screenImage);
            if (r == null) return;
            for (var i = 0; i < r.Length; i++) {
                var result = r[i];
                // 定位点的坐标，按照左下、左上、右上顺序
                float x1 = result.ResultPoints[0].X;
                float y1 = result.ResultPoints[0].Y;
                float x2 = result.ResultPoints[1].X;
                float y2 = result.ResultPoints[1].Y;

                // 计算二维码图片边长
                double interval = (Math.Sqrt(Math.Abs(x1 - x2) * Math.Abs(x1 - x2) + Math.Abs(y1 - y2)
                        * Math.Abs(y1 - y2)));

                // 定位点与起始点的差值
                double deviate = interval * 0.4 / 1.4;

                var length = interval + 2 * deviate;
                // 根据二维码定位坐标计算起始坐标
                var x = Math.Round(x2 - deviate);
                var y = Math.Round(y2 - deviate);

                //再按照缩放比例计算
                var scale = (double)screenCaptureForm.ScreenCaptureImage.Width / screenImage.Width;
                //int qrcodeImgLen = (int)(length * scale);
                //int qrcodeImgX = (int)(x * scale);
                //int qrcodeImgY = (int)(y * scale);
                int qrcodeImgLen = (int)(length);
                int qrcodeImgX = (int)(x);
                int qrcodeImgY = (int)(y);

                var p = new SelectRectangle<Result>(result);
                p.BorderColor = Color.Red;
                p.BorderSize = 3;
                p.BackColor = Color.Transparent;
                p.Width = p.Height = qrcodeImgLen + p.BorderSize * 2;
                p.Left = qrcodeImgX;
                p.Top = qrcodeImgY;
                p.Selected += ScreenCaptureQRCodeSelected;
                screenCaptureForm.SelectPanel.Controls.Add(p);
            }
        }

        private void ScreenCaptureQRCodeSelected(Result obj) {
            screenCaptureForm.EndCapture();
            TxtQRCodeParseResult.Text = obj.Text;
        }
        #endregion


        private void BtnParseClipboardQRCode_Click(object sender, EventArgs e) {
            var img = Clipboard.GetImage();
            if (img == null) {
                TxtQRCodeParseResult.Text = "<剪贴板中没图片!>";
                return;
            }
            Result[] r = QRCodeHelper.ParseQRCode(new Bitmap(img));
            if (r == null) {
                TxtQRCodeParseResult.Text = "<没解析到二维码!>";
                return;
            }
            if (r.Length == 1) {
                TxtQRCodeParseResult.Text = r[0].Text;
            } else {
                TxtQRCodeParseResult.Clear();
                for (int i = 0; i < r.Length; i++) {
                    TxtQRCodeParseResult.AppendText("第" + (i + 1) + "个二维码:\r\n");
                    TxtQRCodeParseResult.AppendText(r[i].Text + "\r\n\r\n");
                }
            }
        }


        private void MainForm_Load(object sender, EventArgs e) {
            TriggerCmdHandler();
        }
        private void MainForm_FormClosed(object sender, FormClosedEventArgs e) {
            screenCaptureForm.Dispose();
        }

    }
}
